<?php

/**
 * productionOrder actions.
 *
 * @package    WacStorehouse
 * @subpackage productionOrder
 * @author     JianBinBi <prince.bi@gmail.com>
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class productionOrderActions extends WacCommonActions
{
   /**
     * get searching list
     * @package
     * @author     ben
     */
  public function executeGetList(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $jqGridDataHelper = JqGridDataHelper::getInstance();

      if(($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && ($request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD)!="")) || $request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
          $arrParam = array();

          if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
              $arrParam['andWhere'] = array(
                      $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
              );
          }
          
          if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

          if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
              switch($request->getParameter(JqGridDataHelper::$KEY_SIDX))
              {
                  case "customer_order_code":
                      $arrParam['orderBy'] = "wco.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "customer_name":
                      $arrParam['orderBy'] = "wc.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "current_workflow_item_name":
                      $arrParam['orderBy'] = "wwfi.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "sample_jar_name":
                      $arrParam['orderBy'] = "wsj.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "goods_amount":
                      $arrParam['orderBy'] = "wpoegi.goods_number ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "goods_category_name":
                      $arrParam['orderBy'] = "wpoegi.goods_category_id ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "status_name":
                      $arrParam['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "customer_name":
                      $arrParam['orderBy'] = "wc.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "maker_name":
                      $arrParam['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  case "auditor_name":
                      $arrParam['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
                  default:
                      $arrParam['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                      break;
              }
          }

          $resultSet = $this->mainModuleTable->getCustomList($arrParam, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
      }
      else {
          $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
      }

      $filterResultSet = $this->filterList($resultSet);

      $pager = $this->mainModuleTable->getPager();
      $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

      return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
  }

  /*
   * override filter list
   */
  public function filterList($listObjs)
  {
      $filterArr = array();
      if(count($listObjs) > 0)
      {
          foreach($listObjs as $listObj)
          {
              $tmpArr = $listObj->toArray();
              $tmpArr['current_workflow_item_name']   = $listObj->getWacWorkflowItem()->getName();
              $tmpArr['goods_amount_unit_code_name']  = $listObj->getWacGoodsAmountUnitCode()->getName();
              $tmpArr['currency_code_name']           = $listObj->getWacCurrency()->getName();
              $tmpArr['customer_order_code']          = $listObj->getWacCustomerOrder()->getCode();
              $tmpArr['customer_name']                = $listObj->getWacCustomer()->getName();
              $tmpArr['maker_name']                   = $listObj->getWacMaker()->getUsername();
              $tmpArr['auditor_name']                 = $listObj->getWacAuditor()->getUsername();
              $tmpArr['sample_jar_name']              = $listObj->getWacSampleJar()->getName();

              $formatDate = new DateTime($listObj->getStartDate());
              $tmpArr['start_date']                   = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getDeliveryDate());
              $tmpArr['delivery_date']                = $formatDate->format("Y-m-d");

              $tmpArr['status_name']                  = StaticWacFormStatus::getCaptionById($listObj->getStatus());

              $estimateItems = $listObj->getWacProductionOrderEstimateGoodsItem();
              $tmpArr['goods_amount']                 = $estimateItems[0]->getGoodsNumber();
              $tmpArr['goods_category_id']            = $estimateItems[0]->getGoodsCategoryId();
              $tmpArr['goods_category_name']          = $estimateItems[0]->getWacGoodsCategory()->getName();
              
              $filterArr[] = $tmpArr;
          }
      }

      return $filterArr;
  }

  /*
   * @return inspect result
   */
  public function inspectDataValidation(sfWebRequest $request, $params=array())
  {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();


      $id = isset($reqParams['id']) ? $reqParams['id'] : 0;
      if($this->mainModuleTable->isExistedCode($reqParams['code'], $id))
      {
         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
         return $result;
      }

      if(empty($reqParams['customer_order_id']) || !Doctrine::getTable(WacTable::$customerOrder)->isExistedId($reqParams['customer_order_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_customer_order"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['goods_category_id']) || !Doctrine::getTable(WacTable::$goodsCategory)->isExistedId($reqParams['goods_category_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_category_not_existed"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['sample_jar_id']) || !Doctrine::getTable(WacTable::$sampleJar)->isExistedId($reqParams['sample_jar_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_sample_jar_not_existed"),  WacErrorCode::$logicError
                  );
         return $result;
      }


//      if($this->mainModuleTable->isExistedName($reqParams['name'], $id))
//      {
//         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['name']), WacErrorCode::$duplicatedName);
//         return $result;
//      }
      return $result;
  }

  /*
   * @return list data array
   */
  public function executeAdd(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $resultSet = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);
      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $reqParams    = $this->getRequest()->getParameterHolder()->getAll();
          $targetItem   = $this->mainModuleTable->create();

          if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              if(isset($reqParams['code']))          {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['customer_order_id']))
              {
                  $objCustomerOrder = Doctrine::getTable(WacTable::$customerOrder)->findOneBy('id', $reqParams['customer_order_id']);
                  $targetItem->setCustomerOrderId($objCustomerOrder->getId());
                  $targetItem->setCustomerId($objCustomerOrder->getCustomerId());
              }

//              if(isset($reqParams['batch'])) {$targetItem->setBatch($reqParams['batch']);}
              if(isset($reqParams['sample_jar_id'])) {$targetItem->setSampleJarId($reqParams['sample_jar_id']);}
              if(isset($reqParams['currency_code'])) {$targetItem->setCurrencyCode($reqParams['currency_code']);}
              if(isset($reqParams['start_date']))    {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date'])) {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}
              if(isset($reqParams['memo']))          {$targetItem->setMemo($reqParams['memo']);}

              $objWorkflow = Doctrine::getTable(WacTable::$workflow)->findOneBy('code', StaticWacWorkFlow::$wfCloth);
              $objWorkflowItem = Doctrine::getTable(WacTable::$workflowItem)->findOneBy('code', StaticWacWorkFlow::$wfClothProductionCreate);
              $targetItem->setWorkflowId($objWorkflow->getId());
              $targetItem->setCurrentWorkflowItemId($objWorkflowItem->getId());

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));

              $targetItem->save();

              $estimateItem = Doctrine::getTable(WacTable::$productionOrderEstimateGoodsItem)->create();
              $estimateItem->setProductionOrderId($targetItem->getId());
              $estimateItem->setCode(WacAppSettingCode::$productionOrderEstimateItemCode);
              $estimateItem->setGoodsCategoryId($reqParams['goods_category_id']);
              $estimateItem->setGoodsNumber($reqParams['goods_amount']);
              $estimateItem->setGoodsNumberUnitCode($reqParams['goods_amount_unit_code']);
              $estimateItem->save();

              $this->afterAdd($request, $targetItem);

          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeEdit(sfWebRequest $request)
  {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('id'));
      
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $resultSet = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);
      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $reqParams  = $this->getRequest()->getParameterHolder()->getAll();
          $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));

          if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
//              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              if(isset($reqParams['code']))          {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['customer_order_id']))
              {
                  $objCustomerOrder = Doctrine::getTable(WacTable::$customerOrder)->findOneBy('id', $reqParams['customer_order_id']);
                  $targetItem->setCustomerOrderId($objCustomerOrder->getId());
                  $targetItem->setCustomerId($objCustomerOrder->getCustomerId());
              }
//              if(isset($reqParams['batch']))         {$targetItem->setBatch($reqParams['batch']);}
              if(isset($reqParams['sample_jar_id'])) {$targetItem->setSampleJarId($reqParams['sample_jar_id']);}
              if(isset($reqParams['currency_code'])) {$targetItem->setCurrencyCode($reqParams['currency_code']);}
              if(isset($reqParams['start_date']))    {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date'])) {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}
              if(isset($reqParams['memo']))          {$targetItem->setMemo($reqParams['memo']);}

              $objWorkflow = Doctrine::getTable(WacTable::$workflow)->findOneBy('code', StaticWacWorkFlow::$wfCloth);
              $objWorkflowItem = Doctrine::getTable(WacTable::$workflowItem)->findOneBy('code', StaticWacWorkFlow::$wfClothProductionCreate);
              $targetItem->setWorkflowId($objWorkflow->getId());
              $targetItem->setCurrentWorkflowItemId($objWorkflowItem->getId());

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));

              $targetItem->save();

              $estimateItems = $targetItem->getWacProductionOrderEstimateGoodsItem();
              $estimateItems[0]->setGoodsCategoryId($reqParams['goods_category_id']);
              $estimateItems[0]->setGoodsNumber($reqParams['goods_amount']);
              $estimateItems[0]->setGoodsNumberUnitCode($reqParams['goods_amount_unit_code']);
              $estimateItems[0]->save();

              $this->afterEdit($request, $targetItem);
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeGetFormData(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }
      
      $resultSet = JsCommonData::getCommonDatum();
      $resultSet['info'] = JsCommonData::getSuccessDatum();

      $resultSet['items']['customer']       = Doctrine::getTable(WacTable::$customer)->getIdNameHash();
      $resultSet['items']['unit']           = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();
      $resultSet['items']['currency']       = Doctrine::getTable(WacTable::$currency)->getCodeNameHash();

      $resultSet['items']['default']['currency_code_name'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$currency);
      $resultSet['items']['default']['cloth_unit_code']    = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$clothUnitCode);



      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
    * @return inspect result
    */
    protected function auditValidation(sfWebRequest $request, $objProductionOrder, $params=array()) {
        $result    = JsCommonData::getSuccessDatum();
        $reqParams = $request->getParameterHolder()->getAll();

        if($objProductionOrder->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
            );
            return $result;
        }

        return $result;
    }

    /*
     * @return list data array
    */
    public function executeAudit(sfWebRequest $request) {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('production_order_id'));

        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = JsCommonData::getCommonDatum();

        $objProductionOrder = Doctrine::getTable(WacTable::$productionOrder)->findOneBy('id', $request->getParameter('production_order_id'));
        $validationResult = $this->auditValidation($request, $objProductionOrder);

        if($validationResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $validationResult;
        }
        else {
            $objProductionOrder->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
            $objProductionOrder->setAuditorId($this->getUser()->getGuardUser()->getId());
            $objProductionOrder->setAuditorDate(format_date(time()));
            $objProductionOrder->save();

            $resultSet['info'] = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }
  
}
